import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, List, Progress, Typography, Button, Space } from 'antd';
import { 
  VideoCameraOutlined, 
  CloudUploadOutlined, 
  CheckCircleOutlined,
  ClockCircleOutlined,
  PrinterOutlined 
} from '@ant-design/icons';
import { useElectronAPI } from '../hooks/useElectronAPI';

const { Title, Text } = Typography;

interface UploadTask {
  id: string;
  fileName: string;
  status: string;
  progress: number;
  platformResults: any;
}

const Dashboard: React.FC = () => {
  const [tasks, setTasks] = useState<UploadTask[]>([]);
  const [stats, setStats] = useState({
    totalUploads: 0,
    successfulUploads: 0,
    pendingUploads: 0,
    totalPlatforms: 0,
  });

  const electronAPI = useElectronAPI();

  useEffect(() => {
    loadDashboardData();
    
    // 监听上传进度
    if (window.electronAPI) {
      window.electronAPI.onUploadProgress((progress: any) => {
        updateTaskProgress(progress);
      });

      window.electronAPI.onPublishProgress((progress: any) => {
        updatePublishProgress(progress);
      });
    }
  }, []);

  const loadDashboardData = async () => {
    try {
      // 获取平台数量
      const platforms = await electronAPI.getPlatforms();
      setStats(prev => ({ ...prev, totalPlatforms: platforms.length }));

      // 这里应该从后端获取真实的统计数据
      // 目前使用模拟数据
      setStats({
        totalUploads: 42,
        successfulUploads: 38,
        pendingUploads: 4,
        totalPlatforms: platforms.length,
      });
    } catch (error) {
      console.error('Failed to load dashboard data:', error);
    }
  };

  const updateTaskProgress = (progress: any) => {
    setTasks(prev => prev.map(task => 
      task.id === progress.taskId 
        ? { ...task, progress: progress.progress, status: progress.status }
        : task
    ));
  };

  const updatePublishProgress = (progress: any) => {
    setTasks(prev => prev.map(task => {
      if (task.id === progress.videoId) {
        const newPlatformResults = { ...task.platformResults };
        newPlatformResults[progress.platformId] = {
          status: progress.status,
          url: progress.url
        };
        return { ...task, platformResults: newPlatformResults };
      }
      return task;
    }));
  };

  const recentTasks = [
    {
      id: '1',
      fileName: 'vlog_2024.mp4',
      status: 'completed',
      progress: 100,
      platformResults: {
        douyin: { status: 'success', url: 'https://douyin.com/video/123' },
        bilibili: { status: 'success', url: 'https://bilibili.com/video/456' }
      }
    },
    {
      id: '2',
      fileName: 'tutorial_react.mp4',
      status: 'processing',
      progress: 75,
      platformResults: {}
    }
  ];

  // 打印功能
  const handlePrint = async () => {
    try {
      // 使用useElectronAPI hook中的打印方法
      const result = await electronAPI.print();
      console.log('打印结果:', result);
    } catch (error) {
      console.error('打印失败:', error);
    }
  };

  // PDF导出功能
  const handleExportPDF = async () => {
    try {
      // 使用useElectronAPI hook中的PDF导出方法
      const result = await electronAPI.printToPDF();
      console.log('PDF导出结果:', result);
    } catch (error) {
      console.error('PDF导出失败:', error);
    }
  };

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
        <Title level={2} style={{ margin: 0 }}>仪表盘</Title>
        <Space>
           <Button 
             type="primary" 
             icon={<PrinterOutlined />} 
             onClick={handlePrint}
             size="middle"
           >
             打印报告
           </Button>
           <Button 
             type="default" 
             icon={<PrinterOutlined />} 
             onClick={handleExportPDF}
             size="middle"
           >
             导出PDF
           </Button>
         </Space>
      </div>
      
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总上传数"
              value={stats.totalUploads}
              prefix={<VideoCameraOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="成功发布"
              value={stats.successfulUploads}
              prefix={<CheckCircleOutlined style={{ color: '#52c41a' }} />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="待处理"
              value={stats.pendingUploads}
              prefix={<ClockCircleOutlined style={{ color: '#faad14' }} />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已连接平台"
              value={stats.totalPlatforms}
              prefix={<CloudUploadOutlined />}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={16}>
        <Col span={16}>
          <Card title="最近上传任务">
            <List
              dataSource={recentTasks}
              renderItem={(task) => (
                <List.Item>
                  <List.Item.Meta
                    title={task.fileName}
                    description={
                      <div>
                        <Progress 
                          percent={task.progress} 
                          status={task.status === 'failed' ? 'exception' : 'normal'}
                          size="small"
                        />
                        <div style={{ marginTop: 8 }}>
                          {Object.entries(task.platformResults).map(([platform, result]: [string, any]) => (
                            <Text key={platform} style={{ marginRight: 16, fontSize: 12 }}>
                              {platform}: {result.status === 'success' ? '✅' : '❌'}
                            </Text>
                          ))}
                        </div>
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card title="平台状态">
            <List
              dataSource={[
                { platform: '抖音', status: '已连接', color: '#52c41a' },
                { platform: '哔哩哔哩', status: '已连接', color: '#52c41a' },
                { platform: '小红书', status: '未连接', color: '#ff4d4f' }
              ]}
              renderItem={(item) => (
                <List.Item>
                  <Text style={{ color: item.color }}>
                    {item.platform}: {item.status}
                  </Text>
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Dashboard;
